'''

	hotbox as menu collection

'''

# coding: utf-8

import sys
from PyQt4 import QtGui, Qt, QtCore

class Test(QtGui.QWidget):
	def __init__(self, parent):
		QtGui.QWidget.__init__(self, parent, QtCore.Qt.Popup)
		if parent is None:
			self.setAttribute(Qt.Qt.WA_QuitOnClose,True)
		self.setWindowOpacity( 0.5 )

		lo = QtGui.QVBoxLayout(self)
		self.setLayout(lo)

		self.setAttribute(Qt.Qt.WA_NoSystemBackground)
		self.setAutoFillBackground(True)

		pixmap = QtGui.QPixmap("test.png")
		width = pixmap.width()
		height = pixmap.height()

		self.setWindowTitle("Status")
    		self.resize(width, height)

    		#self.label = QtGui.QLabel(self)
		#self.label.setPixmap(QtGui.QPixmap("test.png"))
		#lo.addWidget( self.label )

		w = QtGui.QLabel( "test", self )
		w.setWindowOpacity( 1 )
		w.setAutoFillBackground(True)
		w.setBackgroundRole( QtGui.QPalette.Window )
		lo.addWidget( w )
		lo.addStretch( 10 )

    		#self.setMask(pixmap.mask())
		
    	def xpaintEvent(self,event):
		self.setAttribute(Qt.Qt.WA_NoSystemBackground)

class Item(QtGui.QWidget):
	def __init__(self, tool, parent):
		QtGui.QWidget.__init__(
			self, parent, 
			QtCore.Qt.Window
			| QtCore.Qt.FramelessWindowHint
			| QtCore.Qt.WindowStaysOnTopHint
		)
		self.tool = tool

		lo = QtGui.QHBoxLayout()
		#lo.setSpacing(0)

		t = QtGui.QLabel( tool.label, self )

		p = QtGui.QLabel( tool.label, self )
		pixmap = QtGui.QPixmap("test.png").scaledToWidth(16)
		p.setPixmap( pixmap )
		
		lo.addWidget( p )
		lo.addWidget( t )
		self.setLayout(lo)
    		#self.resize(width, height)
		self.setContentsMargins( 0, 0, 0, 0 )
		self.resize( self.sizeHint() )
		
	def mousePressEvent( self, event ):
		QtGui.QWidget.mousePressEvent( self, event )
		self.tool.run(event)

	def mouseReleaseEvent( self, event ):
		QtGui.QWidget.mouseReleaseEvent( self, event )
		if event.globalPos() != self.tool.toolset.callPos:
			self.tool.run(event)

	def keyReleaseEvent( self, event ):
		self.tool.toolset.end()

class Tool:
	def __init__( self, toolset, label, func=None ):
		self.toolset = toolset
		self.label = label
		if func is None:
			func = self.action
		self.func = func
		self.w = None

	def create( self, parent ):
		#print "create", self.label
		if self.w is None:
			self.w = Item( self, parent )
		return self.w

	def show( self, x, y ):
		#print "show", self.label
		self.w.move( x, y )
		self.w.show()
		return self.w

	def close( self ):
		#print "close", self.label
		if self.w is None:
			return
		self.w.close()
		self.w = None
	
	def width( self ):
		return self.w and self.w.width() or 0

	def height( self ):
		return self.w and self.w.height() or 0

	def action(self, *args ):
		if self.label.startswith("sub") or int(self.label.split(' ')[1])%2:
			print self.label, args
			return
		ts = ToolSet( 2 )
		for i in range( 5 ):
			ts.boxes.append(
				Tool( ts, "sub Tool "+str(i).zfill(3)+' '+'#'*i )
			)
		ts.show( QtGui.QCursor.pos(), self.toolset.callerW )

	def run( self, event ):
		ret = self.func(event)
		self.toolset.close()
		return ret

class ToolSet( QtCore.QObject ):
	def __init__( self, nbCol ):
		QtCore.QObject.__init__( self )
		self.nbCol = nbCol
		self.boxes = []
		self.callerW = None
		self.callPos = None

	def eventFilter( self, obj, event ):
		if obj != self.callerW:
			raise Exception("filtered??? "+repr(obj)+" "+repr(self.callerW))
		if event.type() == QtCore.QEvent.KeyRelease:
			self.end()
		elif event.type() == QtCore.QEvent.MouseButtonPress:
			#self.close()
			#self.callerW.setFocus()
			return False
		elif event.type() == QtCore.QEvent.FocusIn:
			print "wcaller focus"
			return True
		return False

	def setBoxes( self, boxList ):
		self.boxes = boxes

	def show( self, pos, parent ):
		if self.callerW is not None:
			return
		self.callerW = parent
		self.callPos = pos
		self.callerW.installEventFilter( self )
		marge = 20
		if pos is None:
			pos = QtCore.QPoint(50,50)

		rows = []
		row = []
		maxW = 0
		maxH = 0
		nbCol = 0
		for i, b in enumerate( self.boxes ):
			b.create(parent)
			nbCol = min( nbCol+1, self.nbCol )
			maxW = max( b.width(), maxW )
			maxH = max( b.height(), maxH )
			row.append( b )
			if not (i+1) % self.nbCol:
				rows.append(row)
				row=[]
		if row:
			rows.append( row )
		nbRow = len(rows )

		width = nbCol * ( maxW + marge ) - marge
		height = nbRow * ( maxH + marge ) - marge

		x = pos.x() - width/2
		y = pos.y() - height/2
		for row in rows:
			for i in row:
				i.show(x, y)
				x += maxW + marge
			y += maxH + marge
			x = pos.x() - width/2
		
		return True

	def close(self):
		for b in self.boxes:
			b.close()

	def end(self):
		self.close()
		self.callerW.setFocus()
		self.callerW.removeEventFilter(self)
		self.callerW = None

if __name__ == "__main__":
	app = QtGui.QApplication(sys.argv)
	w = QtGui.QFrame(None)
	w.show()
	ts = ToolSet( 5 )
	for i in range( 12 ):
		ts.boxes.append(
			Tool( ts, "Tool "+str(i).zfill(3)+' '+'#'*i )
		)
	def mainKeyPressEvent( event ):
		if event.key() == QtCore.Qt.Key_Space:
			ts.show( QtGui.QCursor.pos(), w )
		else:
			QtGui.QFrame.keyPressEvent( w, event )
	w.keyPressEvent = mainKeyPressEvent
	app.exec_()

